﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace System.Web
{
    public static class HttpResponseExtensions
    {
        public static void CopyTo(this Stream stream, Stream destination)
        {
            byte[] buffer = new byte[1024];
            int read;
            while ((read = stream.Read(buffer, 0, buffer.Length)) != 0)
                destination.Write(buffer, 0, read);
        }
        public static void CopyFrom(this HttpListenerResponse response, Stream source)
        {
            source.CopyTo(response.OutputStream);
        }
        public static void WriteFile(this HttpListenerResponse response, string fileName)
        {
            string fileExtension = Path.GetExtension(fileName);
            switch (fileExtension)
            {
                case ".js":response.ContentType = "text/javascript; charset=utf-8";break;
                case ".html":response.ContentType = "text/html; charset=utf-8";break;
                case ".htm": response.ContentType = "text/html; charset=utf-8"; break;
                case ".css":response.ContentType = "text/css; charset=utf-8"; break;
                case ".jpg": response.ContentType = "image/jpg"; break;
                case ".png": response.ContentType = "image/png"; break;
                case ".gif": response.ContentType = "image/gif"; break;
                case ".jpeg": response.ContentType = "image/jpeg"; break;
                default: response.ContentType = "text/html; charset=utf-8"; break;
            }
            using (FileStream stream = new FileStream(fileName,FileMode.Open,FileAccess.Read,FileShare.Read,9810))
            {
                stream.CopyTo(response.OutputStream);
            }
        }
        public static void Write(this HttpListenerResponse response, byte[] buffer, int offset, int length)
        {
            response.OutputStream.Write(buffer, offset, length);
        }
        public static void Write(this HttpListenerResponse response, string content)
        {
            byte[] buffer = Constant.encoding.GetBytes(content);
            response.Write(buffer, 0, buffer.Length);
        }
        public static void Write(this HttpListenerResponse response, object content)
        {
            if (content != null)
            {
                byte[] buffer = Constant.encoding.GetBytes(content.ToString());
                response.Write(buffer, 0, buffer.Length);
            }
        }
        public static void End(this HttpListenerResponse response)
        {
            response.OutputStream.Flush();
            response.OutputStream.Close();
        }
    }
}
